#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os

from git import Git

select = input("请选择：1. 全部切换\n 2 .部分切换\n")
check_branch = input('请输入分支名称：\n')
remote_lib = input('请输入远程库名称：\n')
parentPath = os.getcwd()

def git_execue(pathStr):
    print("进入目录："+pathStr)
    os.chdir(parentPath+'/'+pathStr)
    path = os.getcwd()
    print('已经进入目录：'+path)
    current_repo = Git(path)
    print('执行fetch命令：'+current_repo.execute('git fetch --all'))
    branch = current_repo.execute('git symbolic-ref --short -q HEAD')
    print('当前分支：'+branch)
    
    branch_list = current_repo.execute('git branch')
    print('分支列表：\n'+branch_list)
    if(branch_list.find(check_branch)==-1):
        print('创建分支：'+current_repo.execute('git fetch ' +
                                        remote_lib + " " + check_branch+":"+check_branch))
        print('切换分支：'+current_repo.execute('git checkout '+check_branch))



print("当前工作目录：\n"+parentPath)
if select =='1':
    print("开始进行全部切换\n")
    for pathStr in os.listdir(parentPath):
        if(pathStr.find('ccb') != -1):
            git_execue(pathStr)
            
elif select=='2':
    select = input("请选择：\n 1，从文件读取\n 2,手动输入")
    code_lib_list = []
    if select == '1':
        with open(parentPath+'/commit.txt','r') as f:
            for line in f.readlines():
                line = line.strip('\n')
                if line.find('#')==-1:
                    code_lib_list.append(line) 
            pass
    else:
        code_libs=input("请输入库的目录名称，多个库请使用','分隔：\n")
        code_lib_list = code_libs.split(',')
    print("开始进行部分切换")
    for pathStr in code_lib_list:
        git_execue(pathStr)
        
else :
    print('请输入正确选项')
